﻿using System.Collections.Concurrent;
using System.Collections.Generic;
using ZilLion.Service.Core.WebSocket.Interface;

namespace ZilLion.Service.Core.WebSocket.MessagePersistence
{
    public class LocalMessagePersistenceHandle : IMessagePersistenceHandle
    {
        private readonly object _createQueLock = new object();

        private readonly ConcurrentDictionary<string, ConcurrentQueue<SocketMessage>> _meesageContainer =
            new ConcurrentDictionary<string, ConcurrentQueue<SocketMessage>>();

        public void SaveMessage(string clientKey, SocketMessage socketMessage)
        {
            if (!_meesageContainer.TryGetValue(clientKey, out var queue)) return;
            if (queue == null)
                lock (_createQueLock)
                {
                    queue = new ConcurrentQueue<SocketMessage>();
                    queue.Enqueue(socketMessage);
                }
            else
                queue.Enqueue(socketMessage);
        }

        public IList<SocketMessage> GetMessage(string clientKey)
        {
            IList<SocketMessage> result = new List<SocketMessage>();
            if (!_meesageContainer.TryGetValue(clientKey, out var queue)) return result;
            if (queue == null) return result;
            while (queue.TryDequeue(out var message))
                result.Add(message);

            return result;
        }
    }
}